#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Linux底层对抗能力优化 - 功能演示脚本
Demonstration Script for Linux Anti-Confrontation Capabilities

该脚本演示所有新功能模块的集成使用：
1. 内核版本检测和策略映射
2. EDR检测和规避策略
3. BPF动态追踪对抗
4. 痕迹清理闭环验证
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

import os
import sys
import time
import json

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

try:
    from modules.environment import KernelDetector, EnvironmentAnalyzer, KernelCapabilities
    from modules.security import EDRScanner, EDREvader, BPFDetector, BPFEvader, BPFEvasionManager
    from modules.cleaner import TraceVerifier, CleanupValidator, TraceCleanupManager
except ImportError as e:
    print(f"[!] 模块导入失败: {e}")
    print("[*] 请确保所有模块都已正确安装")
    sys.exit(1)


def print_banner():
    """打印横幅"""
    banner = """
╔══════════════════════════════════════════════════════════════════════════════╗
║                    Linux底层对抗能力优化 - 功能演示                           ║
║                  Linux Anti-Confrontation Capabilities Demo                 ║
╠══════════════════════════════════════════════════════════════════════════════╣
║  功能模块:                                                                   ║
║  • 内核版本动态适配框架                                                      ║
║  • EDR特征库动态更新机制                                                     ║
║  • BPF动态追踪对抗                                                          ║
║  • 痕迹清理闭环验证                                                          ║
╚══════════════════════════════════════════════════════════════════════════════╝
    """
    print(banner)


def demo_kernel_detection():
    """演示内核检测功能"""
    print("\n" + "="*60)
    print("1. 内核版本检测和策略映射演示")
    print("="*60)
    
    try:
        # 环境分析
        print("[*] 启动环境分析器...")
        analyzer = EnvironmentAnalyzer()
        
        print("[*] 执行完整环境分析...")
        analysis_result = analyzer.full_analysis()
        
        if analysis_result:
            kernel_info = analysis_result.get('kernel_info', {})
            capabilities = analysis_result.get('capabilities', {})
            
            print(f"[+] 系统类型: {kernel_info.get('system', 'Unknown')}")
            print(f"[+] 内核版本: {kernel_info.get('version_string', 'Unknown')}")
            print(f"[+] 发行版: {kernel_info.get('distribution', 'Unknown')}")
            print(f"[+] 架构: {kernel_info.get('machine', 'Unknown')}")
            
            # 显示可用能力
            available_capabilities = [k for k, v in capabilities.items() if v]
            print(f"[+] 可用特性: {len(available_capabilities)}")
            
            if available_capabilities:
                print("    可用特性列表:")
                for cap in available_capabilities[:5]:  # 只显示前5个
                    print(f"    • {cap}")
                if len(available_capabilities) > 5:
                    print(f"    ... 还有 {len(available_capabilities) - 5} 个特性")
            
            # 策略推荐
            print("\n[*] 获取策略推荐...")
            operations = ['fileless_execution', 'process_injection', 'privilege_escalation']
            for op in operations:
                strategy = analyzer.get_strategy_recommendation(op)
                if strategy:
                    print(f"[+] {op}: {strategy.get('method', 'Unknown')}")
        
        return True
        
    except Exception as e:
        print(f"[!] 内核检测演示失败: {e}")
        return False


def demo_edr_detection():
    """演示EDR检测功能"""
    print("\n" + "="*60)
    print("2. EDR检测和规避策略演示")
    print("="*60)
    
    try:
        print("[*] 启动EDR扫描器...")
        scanner = EDRScanner()
        
        print("[*] 执行完整EDR扫描...")
        scan_results = scanner.full_scan()
        
        if scan_results:
            detected_edrs = scan_results.get('detected_edrs', [])
            scan_summary = scan_results.get('scan_summary', {})
            
            print(f"[+] 检测到EDR产品: {len(detected_edrs)}")
            
            if detected_edrs:
                print("    检测到的EDR:")
                for edr in detected_edrs:
                    confidence = edr.get('confidence', 0)
                    print(f"    • {edr.get('name', 'Unknown')} (置信度: {confidence:.1%})")
            else:
                print("    [*] 未检测到已知EDR产品")
            
            # 显示扫描统计
            print(f"[+] 扫描统计:")
            print(f"    • 进程扫描: {scan_summary.get('processes_scanned', 0)}")
            print(f"    • 文件扫描: {scan_summary.get('files_scanned', 0)}")
            print(f"    • 服务扫描: {scan_summary.get('services_scanned', 0)}")
            
            # 规避策略
            print("\n[*] 生成规避策略...")
            evader = EDREvader(scan_results)
            
            if detected_edrs:
                print("[*] 应用针对性规避策略...")
                evader.apply_evasion_strategies(detected_edrs)
            else:
                print("[*] 应用通用规避策略...")
                evader.apply_evasion_strategies(['generic'])
        
        return True
        
    except Exception as e:
        print(f"[!] EDR检测演示失败: {e}")
        return False


def demo_bpf_evasion():
    """演示BPF规避功能"""
    print("\n" + "="*60)
    print("3. BPF动态追踪对抗演示")
    print("="*60)
    
    try:
        print("[*] 启动BPF规避管理器...")
        manager = BPFEvasionManager(enable_auto_evasion=False)
        
        print("[*] 执行完整BPF分析...")
        analysis_results = manager.full_bpf_analysis()
        
        if analysis_results:
            bpf_status = analysis_results.get('bpf_enabled', {})
            loaded_programs = analysis_results.get('loaded_programs', [])
            monitoring_detected = analysis_results.get('monitoring_detected', False)
            
            print(f"[+] BPF支持状态: {'启用' if bpf_status.get('enabled', False) else '禁用'}")
            print(f"[+] 已加载BPF程序: {len(loaded_programs)}")
            print(f"[+] 监控检测: {'是' if monitoring_detected else '否'}")
            
            if loaded_programs:
                print("    已加载的BPF程序:")
                for i, prog in enumerate(loaded_programs[:3]):  # 只显示前3个
                    print(f"    • 程序 {i+1}: {prog.get('type', 'Unknown')}")
                if len(loaded_programs) > 3:
                    print(f"    ... 还有 {len(loaded_programs) - 3} 个程序")
            
            # 规避建议
            evasion_recommendations = analysis_results.get('evasion_recommendations', [])
            if evasion_recommendations:
                print("\n[+] BPF规避建议:")
                for rec in evasion_recommendations[:3]:
                    print(f"    • {rec}")
        
        return True
        
    except Exception as e:
        print(f"[!] BPF规避演示失败: {e}")
        return False


def demo_trace_verification():
    """演示痕迹验证功能"""
    print("\n" + "="*60)
    print("4. 痕迹清理闭环验证演示")
    print("="*60)
    
    try:
        print("[*] 启动痕迹清理管理器...")
        manager = TraceCleanupManager()
        
        # 模拟清理目标
        cleanup_targets = {
            'log_files': ['/var/log/auth.log', '/var/log/syslog'],
            'command_history': ['/home/user/.bash_history'],
            'process_traces': ['suspicious_process'],
            'network_connections': ['192.168.1.100:4444']
        }
        
        print("[*] 执行痕迹验证...")
        verifier = TraceVerifier()
        verification_results = verifier.verify_cleanup_effectiveness(cleanup_targets)
        
        if verification_results:
            total_traces = verification_results.get('total_traces_found', 0)
            effectiveness = verification_results.get('cleanup_effectiveness', 0)
            remaining_traces = verification_results.get('remaining_traces', [])
            
            print(f"[+] 发现痕迹总数: {total_traces}")
            print(f"[+] 清理效果: {effectiveness:.1f}%")
            
            if remaining_traces:
                print(f"[!] 残留痕迹: {len(remaining_traces)}")
                for trace in remaining_traces[:3]:
                    print(f"    • {trace.get('type', 'Unknown')}: {trace.get('location', 'Unknown')}")
            else:
                print("[+] 未发现残留痕迹")
        
        print("\n[*] 执行安全验证...")
        validator = CleanupValidator()
        safety_results = validator.validate_cleanup_safety(cleanup_targets)
        
        if safety_results:
            safe_to_proceed = safety_results.get('safe_to_proceed', False)
            safety_score = safety_results.get('safety_score', 0)
            warnings = safety_results.get('warnings', [])
            
            print(f"[+] 安全检查: {'通过' if safe_to_proceed else '失败'}")
            print(f"[+] 安全评分: {safety_score:.1f}/100")
            
            if warnings:
                print(f"[!] 安全警告: {len(warnings)}")
                for warning in warnings[:2]:
                    print(f"    • {warning}")
        
        return True
        
    except Exception as e:
        print(f"[!] 痕迹验证演示失败: {e}")
        return False


def demo_integration_workflow():
    """演示完整集成工作流"""
    print("\n" + "="*60)
    print("5. 完整集成工作流演示")
    print("="*60)
    
    try:
        print("[*] 启动完整对抗能力工作流...")
        
        # 步骤1: 环境分析
        print("\n[步骤1] 环境分析...")
        analyzer = EnvironmentAnalyzer()
        env_result = analyzer.full_analysis()
        
        if not env_result:
            print("[!] 环境分析失败")
            return False
        
        print("[+] 环境分析完成")
        
        # 步骤2: EDR检测
        print("\n[步骤2] EDR检测...")
        scanner = EDRScanner()
        edr_result = scanner.full_scan()
        
        if not edr_result:
            print("[!] EDR检测失败")
            return False
        
        detected_edrs = edr_result.get('detected_edrs', [])
        print(f"[+] EDR检测完成，发现 {len(detected_edrs)} 个EDR产品")
        
        # 步骤3: BPF分析
        print("\n[步骤3] BPF监控分析...")
        bpf_manager = BPFEvasionManager(enable_auto_evasion=False)
        bpf_result = bpf_manager.full_bpf_analysis()
        
        if not bpf_result:
            print("[!] BPF分析失败")
            return False
        
        monitoring_detected = bpf_result.get('monitoring_detected', False)
        print(f"[+] BPF分析完成，监控状态: {'检测到' if monitoring_detected else '未检测到'}")
        
        # 步骤4: 策略选择
        print("\n[步骤4] 策略选择...")
        
        # 基于环境分析结果选择最优策略
        kernel_info = env_result.get('kernel_info', {})
        capabilities = env_result.get('capabilities', {})
        
        # 选择文件执行策略
        if capabilities.get('memfd_secret', False):
            execution_strategy = "memfd_secret"
        elif capabilities.get('memfd_create', False):
            execution_strategy = "memfd_create"
        else:
            execution_strategy = "tmpfs + unlink"
        
        print(f"[+] 推荐执行策略: {execution_strategy}")
        
        # 选择规避策略
        if detected_edrs:
            evasion_strategy = "针对性规避"
        elif monitoring_detected:
            evasion_strategy = "BPF对抗"
        else:
            evasion_strategy = "通用隐蔽"
        
        print(f"[+] 推荐规避策略: {evasion_strategy}")
        
        # 步骤5: 痕迹管理
        print("\n[步骤5] 痕迹管理...")
        trace_manager = TraceCleanupManager()
        
        # 模拟操作后的痕迹清理
        cleanup_targets = {
            'execution_traces': [execution_strategy],
            'evasion_traces': [evasion_strategy],
            'analysis_traces': ['environment_scan', 'edr_scan', 'bpf_scan']
        }
        
        verifier = TraceVerifier()
        verification_result = verifier.verify_cleanup_effectiveness(cleanup_targets)
        
        effectiveness = verification_result.get('cleanup_effectiveness', 0)
        print(f"[+] 痕迹清理效果: {effectiveness:.1f}%")
        
        # 生成最终报告
        print("\n[步骤6] 生成对抗能力报告...")
        
        final_report = {
            'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
            'environment': {
                'system': kernel_info.get('system', 'Unknown'),
                'kernel_version': kernel_info.get('version_string', 'Unknown'),
                'available_features': len([k for k, v in capabilities.items() if v])
            },
            'threats': {
                'detected_edrs': len(detected_edrs),
                'bpf_monitoring': monitoring_detected,
                'threat_level': 'High' if detected_edrs or monitoring_detected else 'Low'
            },
            'strategies': {
                'execution': execution_strategy,
                'evasion': evasion_strategy,
                'cleanup_effectiveness': effectiveness
            },
            'recommendations': [
                f"使用 {execution_strategy} 进行无文件执行",
                f"采用 {evasion_strategy} 策略规避检测",
                f"确保痕迹清理效果达到 {effectiveness:.1f}%"
            ]
        }
        
        # 保存报告
        report_path = os.path.join(project_root, 'anti_confrontation_report.json')
        with open(report_path, 'w', encoding='utf-8') as f:
            json.dump(final_report, f, indent=2, ensure_ascii=False)
        
        print(f"[+] 对抗能力报告已保存到: {report_path}")
        
        return True
        
    except Exception as e:
        print(f"[!] 集成工作流演示失败: {e}")
        return False


def main():
    """主函数"""
    print_banner()
    
    demos = [
        ("内核检测", demo_kernel_detection),
        ("EDR检测", demo_edr_detection),
        ("BPF规避", demo_bpf_evasion),
        ("痕迹验证", demo_trace_verification),
        ("集成工作流", demo_integration_workflow)
    ]
    
    success_count = 0
    total_demos = len(demos)
    
    for demo_name, demo_func in demos:
        try:
            print(f"\n{'='*20} 开始演示: {demo_name} {'='*20}")
            
            if demo_func():
                success_count += 1
                print(f"[+] {demo_name} 演示成功")
            else:
                print(f"[!] {demo_name} 演示失败")
                
        except KeyboardInterrupt:
            print(f"\n[*] 用户中断演示")
            break
        except Exception as e:
            print(f"[!] {demo_name} 演示异常: {e}")
    
    # 总结
    print("\n" + "="*60)
    print("演示总结")
    print("="*60)
    print(f"总演示数: {total_demos}")
    print(f"成功演示: {success_count}")
    print(f"失败演示: {total_demos - success_count}")
    print(f"成功率: {(success_count/total_demos*100):.1f}%")
    
    if success_count == total_demos:
        print("\n[+] 所有功能演示成功！Linux底层对抗能力优化已完成。")
    else:
        print(f"\n[*] {total_demos - success_count} 个演示失败，请检查相关模块。")
    
    print("\n感谢使用Linux底层对抗能力优化系统！")


if __name__ == "__main__":
    main()